package com.hzdl.test;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import org.junit.Test;

import java.lang.reflect.Method;

/**
 * @author ：Reus CAI
 * @date ：Created in 2020/12/17 15:33
 * @description：Enhance实现动态代理
 * @modified By：
 * @version: $
 */


public class DynamicProxyDemo {

    Lenovo lenovo = new Lenovo();

    public void exeDynamic(Double sale) {

        Lenovo newComputer = (Lenovo) Enhancer.create(Lenovo.class, new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {

                /*
                Attention: 参数Object o, 指的是被代理类对象, 在这里就是lenovo对象.
                * */

                if (method.getName().equals("buyGoods")) {
                    Double oldPrice = (Double) objects[0];
                    Double newPrice = oldPrice * sale;
                    Object invoke = method.invoke(lenovo, newPrice);
                    return invoke;

                } else {
                    return method.invoke(lenovo, objects);
                }

            }
        });


        String s = newComputer.buyGoods(10000.0);
        System.out.println(s);
    }


    @Test
    public void methodTest() {


        exeDynamic(0.6);

    }

}


class Lenovo {

    public String buyGoods(Double price) {
        String out = "给你一台联想电脑, 价格为:" + price;
        return out;
    }


}
